/* eslint-disable @typescript-eslint/no-shadow */
import React, {
  JSX,
  memo,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Image,
  LayoutChangeEvent,
  Animated,
  PanResponder,
  TouchableOpacity,
} from 'react-native';
import {Item, source} from './data';
import {BasicText} from '../../kit/text';
import {normalize} from '../../utils/adapter';
import ErrorBoundary from '../../kit/com/ErrorBoundary';
import {HorizontalSkeleton} from '../../kit/skeleton';
import {ScreenHeight} from '../../config/devices';

type ItemProps = {} & Item;

type RemoveBtnProps = {
  height: number;
  offsetX: number;
};

const RemoveBtn = memo(function ({height, offsetX}: RemoveBtnProps) {
  const translateX = useRef(new Animated.Value(offsetX)).current;

  useEffect(() => {
    Animated.timing(translateX, {
      toValue: offsetX,
      duration: 200,
      useNativeDriver: false,
    }).start();
  }, [offsetX, translateX]);

  return (
    <Animated.View
      style={[{height}, styles.remove_btn_view, {transform: [{translateX}]}]}>
      <TouchableOpacity style={[{height}, styles.remove_btn_view]}>
        <BasicText color="#fff" fontSize={normalize(12)}>
          删除
        </BasicText>
      </TouchableOpacity>
    </Animated.View>
  );
});

const HistoryListItem = memo(function ({
  cover,
  title,
  subtitle,
  episodesNum,
}: ItemProps) {
  const [height, setheight] = useState(0);
  const [offsetX, setOffsetX] = useState(100);
  const SWIPE_THRESHOLD = 80;

  const onLayout = useCallback((e: LayoutChangeEvent) => {
    const {height} = e.nativeEvent.layout;
    setheight(height);
  }, []);

  const panResponder = useRef(
    PanResponder.create({
      // 只有在水平方向滑动比垂直方向大时，才激活panResponder
      onMoveShouldSetPanResponderCapture(e, gestureState) {
        return Math.abs(gestureState.dx) > Math.abs(gestureState.dy);
      },
      onPanResponderRelease(e, gestureState) {
        if (gestureState.dx <= -SWIPE_THRESHOLD) {
          setOffsetX(0);
        }
        if (gestureState.dx >= SWIPE_THRESHOLD) {
          setOffsetX(100);
        }
      },
    }),
  ).current;

  return (
    <View
      style={styles.item_contianer}
      onLayout={onLayout}
      {...panResponder.panHandlers}>
      <Image source={cover} style={styles.item_image} resizeMode={'cover'} />
      <View style={styles.item_contant}>
        <View>
          <Text style={styles.item_title}>{title}</Text>
          <Text style={styles.item_subtitle}>{subtitle}</Text>
        </View>
        <View>
          <Text style={styles.item_episodesNum}>{episodesNum}集全</Text>
        </View>
      </View>
      <RemoveBtn height={height} offsetX={offsetX} />
    </View>
  );
});

function HistoryScreen(): JSX.Element {
  const [data] = useState(source);

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        renderItem={props => <HistoryListItem {...props.item} />}
        keyExtractor={item => item.id as unknown as string}
      />
    </View>
  );
}

const Skeleton = function () {
  return (
    <View
      style={{
        height: ScreenHeight,
        backgroundColor: '#fff',
        paddingHorizontal: normalize(12),
      }}>
      <HorizontalSkeleton />
      <HorizontalSkeleton />
      <HorizontalSkeleton />
      <HorizontalSkeleton />
      <HorizontalSkeleton />
      <HorizontalSkeleton />
      <HorizontalSkeleton />
      <HorizontalSkeleton />
    </View>
  );
};

export default () => (
  <ErrorBoundary skeleton={<Skeleton />}>
    <HistoryScreen />
  </ErrorBoundary>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item_contianer: {
    flexDirection: 'row',
    padding: normalize(12),
    backgroundColor: '#fff',
    position: 'relative',
    marginBottom: 5,
  },
  item_image: {
    width: normalize(71),
    height: normalize(100),
  },
  item_contant: {
    marginLeft: normalize(12),
    flex: 1,
    justifyContent: 'space-around',
  },
  item_title: {
    color: '#333',
    fontWeight: 'bold',
    fontSize: normalize(14),
  },
  item_subtitle: {
    color: '#FF7F39',
    fontWeight: 'medium',
    fontSize: normalize(10),
    marginTop: normalize(10),
  },
  item_episodesNum: {
    color: '#999999',
    fontSize: normalize(10),
    fontWeight: 'medium',
  },
  remove_btn_view: {
    position: 'absolute',
    right: normalize(0),
    backgroundColor: '#F56C6C',
    borderTopLeftRadius: normalize(6),
    borderBottomLeftRadius: normalize(6),
    width: normalize(80),
    justifyContent: 'center',
    alignItems: 'center',
  },
});
